package com.simpd.activity;

import java.util.ArrayList;
import java.util.List;

import com.example.simpd.R;
import com.simpd.db_helper.DatabaseHelper;
import com.simpd.model.NotifikasiSKPD;
import com.simpd.model.SynchronizeConstant;
import com.simpd.my_list_view.CustomAdapter;
import com.simpd.my_list_view.RowItem;
import com.simpd.my_spinner.NoDefaultSpinner;

import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

public class NotificationActivity extends Activity {
	
	public static boolean dataChange; 
	public static int locationChange;
	
	
	ImageButton btnBack; 
	Switch swithcer; 
	ListView list; 
	NoDefaultSpinner spinner; 
	RelativeLayout emptyView;
	
	private CustomAdapter adapter;

	private String[] spinnerOptions;
	private String unip;
	
	private int[] idsNotifikasi;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		getActionBar().hide();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notifikasi_activity);
		
		btnBack 	= (ImageButton) findViewById(R.id.notifikasi_button_back); 
		swithcer	= (Switch) findViewById(R.id.notifikasi_switcher); 
		list 		= (ListView) findViewById(R.id.notifikasi_listview_list); 
		spinner		= (NoDefaultSpinner) findViewById(R.id.notifikasi_spinner); 
		emptyView	= (RelativeLayout) findViewById(R.id.notifikasi_empty);
		spinnerOptions = new String[] {"semua notifikasi", "sudah dibaca", 
				 "belum dibaca", "tanggal terbaru", 
				 "tanggal terlama", "filter skpd"};

		ArrayAdapter<String> adapterSpinner = new ArrayAdapter<String>(this, 
			       R.layout.spinner_item, 
			       spinnerOptions);
		spinner.setAdapter(adapterSpinner);
		
		unip = getIntent().getExtras().getString("unip", "196206062012011001_default");
		
		
		setAdapterDefaultData();
		
		
		
		btnBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		swithcer.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					spinner.setVisibility(View.VISIBLE);
				}else{
					spinner.setVisibility(View.GONE);
				}
			}
		});
		
		spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				ArrayList<NotifikasiSKPD> arraylist = null;
				DatabaseHelper db = new DatabaseHelper(getApplicationContext());
				String message = "Semua Notifikasi";
				
				switch (position) {
				case SynchronizeConstant.DEFAULT_NOTIF:
					setAdapterDefaultData(); 
					message = "Semua Notifikasi";
					break;
				case SynchronizeConstant.HAS_READ : 
					// has read, status = 1
					arraylist = db.getAllNotifikasiWhere(DatabaseHelper.KEY_STATUS+" = ? ", 
														 new String[] {String.valueOf(DatabaseHelper.STATUS_READ)});
					// adapter.filterHasRead(true);
					updateAdapterListView(arraylist);
					message = "Notifikasi yang sudah terbaca!"; 
					break; 
				case SynchronizeConstant.NOT_READ : 
					arraylist = db.getAllNotifikasiWhere(DatabaseHelper.KEY_STATUS+" = ?", 
														new String[] {String.valueOf(DatabaseHelper.STATUS_NOT_READ)});;
					// adapter.filterHasRead(false);
					updateAdapterListView(arraylist);									
					message = "Notifikasi yang belum terbaca!"; 
					break; 
				case SynchronizeConstant.NEWLY : 
					arraylist = db.getAllNotifikasi(DatabaseHelper.KEY_TANGGAL_UPDATE , false); 
					updateAdapterListView(arraylist);
					message = "Notifikasi paling baru!";
					break; 
				case SynchronizeConstant.OLD : 
					arraylist = db.getAllNotifikasi(DatabaseHelper.KEY_TANGGAL_UPDATE, true); 
					updateAdapterListView(arraylist);
					message = "Notifikasi paling lama!"; 
					break; 
					
				case (SynchronizeConstant.FILTER_SKPD - 1) :
					showPopupSkpd(); 
					message = "Filter Notifikasi berdasarkan SKPD";
					break;
				default:
					message = "opsi tidak tersedia !";
					break;
				}
				Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();
		if(dataChange==true){
			RowItem item = (RowItem) adapter.getItem(locationChange);
			int updateIcon = item.getIconId() == R.drawable.icon_spt || item.getIconId() == R.drawable.icon_spt_signature ? 
					R.drawable.icon_spt_signature : R.drawable.icon_tlh_signature;
			item.setIconId(updateIcon);
			adapter.setItem(locationChange, item);
			adapter.notifyDataSetChanged();
			list.invalidate();
			Log.d("[onResume]", "update adapter with position : "+locationChange);
			dataChange  	= false;
			locationChange  = 1000;
		}
	}
	
	/**
	 * type void 
	 * used to set data to show all default notifications
	 */
	private void setAdapterDefaultData(){
		DatabaseHelper db = new DatabaseHelper(this);
		ArrayList<NotifikasiSKPD> allNotifikasi = db.getAllNotifikasi(DatabaseHelper.KEY_TANGGAL_UPDATE, false);
		updateAdapterListView(allNotifikasi);
	}
	
	/**
	 * @param data
	 * used to update item of list view base on arraylist data
	 */
	private void updateAdapterListView(ArrayList<NotifikasiSKPD> data){
		// get data notifikasi from database
		List<RowItem> rowItems = new ArrayList<RowItem>();
		RowItem row = null;
		String tanggal = null;
		idsNotifikasi = new int[data.size()];
		int i = 0;
		int tempIcon = 0;
		for (NotifikasiSKPD notifikasi : data) {
			row = new RowItem();
			
			tempIcon = 0;
			if(notifikasi.getTipeSurat().equalsIgnoreCase("telaah")){
				tempIcon = notifikasi.getStatus() == 2 ? R.drawable.icon_tlh_signature : R.drawable.icon_tlh;
			}else{
				tempIcon = notifikasi.getStatus() == 2 ? R.drawable.icon_spt_signature : R.drawable.icon_spt;
			}
			
			row.setIconId(tempIcon);
			row.setTitle(notifikasi.getSkpd());
			row.setSubtitle(notifikasi.getPerihal());
			tanggal = notifikasi.getTanggalUpdate().substring(0, 10);
			tanggal = tanggal.replace("-", "/");
			row.setValue(tanggal);
			
			if(notifikasi.getStatus() == 0) 
				row.hasRead(false);
			else
				row.hasRead(true); 
			
			rowItems.add(row);
			Log.d("[notifikasi-id]", "id notifikasi : "+notifikasi.getId());
			idsNotifikasi[i] = notifikasi.getId();
			i++;
		}
		
		adapter = new CustomAdapter(this, rowItems);
		list.setAdapter(adapter);
	
		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				DatabaseHelper db = new DatabaseHelper(getApplicationContext()); 
				NotifikasiSKPD notifikasi = db.getNotifikasi(idsNotifikasi[position]);
				Log.d("[notifikasi-row]", "get notifikasi dengan id : "+idsNotifikasi[position]);
				if(notifikasi.getStatus()==0){
					notifikasi.setStatus(1);
					db.update(idsNotifikasi[position], notifikasi);
					
					RowItem rowItem = (RowItem) adapter.getItem(position);
					rowItem.hasRead(true);
					adapter.setItem(position, rowItem);
					adapter.notifyDataSetChanged();
				}
				Intent intent = new Intent(NotificationActivity.this, DetailNotifikasiActivity.class);
				intent.putExtra("unip", unip);
				intent.putExtra("url", notifikasi.getOnlineUrl());
				intent.putExtra("id", notifikasi.getId());
				intent.putExtra("position", position);
				intent.putExtra("sebagai", notifikasi.getSebagai());
				startActivity(intent);
			}
		});
		if(list.getAdapter().isEmpty()==true){
			list.setVisibility(View.GONE); 
			emptyView.setVisibility(View.VISIBLE);
		}else{
			emptyView.setVisibility(View.GONE);
			list.setVisibility(View.VISIBLE); 
		}
				
	}
	
	/**
	 * type void 
	 * digunakan untuk menampilkan pop up window yang berisi
	 * list skpd 
	 */
	public void showPopupSkpd(){
		LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View view = layoutInflater.inflate(R.layout.popup_window, null); 
		final PopupWindow popup = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,true);
		
		popup.setAnimationStyle(R.style.popupAnimationUpDown);
		
		TextView title 		= (TextView) view.findViewById(R.id.popup_title); 
		ListView listPopup 	= (ListView) view.findViewById(R.id.popup_list);
		Button btnDismiss 	= (Button) view.findViewById(R.id.popup_button_dismiss);
		
		title.setText("Pilih jenis SKPD");
		title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
		title.setTextColor(Color.BLUE);
		
		btnDismiss.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				popup.dismiss();
			}
		});
		
		DatabaseHelper db = new DatabaseHelper(this);
		ArrayList<String> jenisSkpd = db.getDistinctSkpd();
		
		final List<RowItem> rowPopup = new ArrayList<RowItem>();
		RowItem item = null;
		for (String skpd : jenisSkpd) {
			item = new RowItem(); 
			item.setIconId(R.drawable.icon_stack); 
			item.setTitle(skpd); 
			item.setSubtitle("filter notifikasi dengan jenis skpd : "+skpd);
			item.setValue("");
			rowPopup.add(item);
		}
		
		CustomAdapter adapterPopup = new CustomAdapter(this, rowPopup);
		adapterPopup.setOffsetDefault(5);
		listPopup.setAdapter(adapterPopup);
		
		listPopup.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String selectedSkpd = rowPopup.get(position).getTitle();
				DatabaseHelper db = new DatabaseHelper(NotificationActivity.this);
				ArrayList<NotifikasiSKPD> arraylist = null;
				arraylist = db.getAllNotifikasiWhere(DatabaseHelper.KEY_SKPD+" = ? ", new String[]{selectedSkpd});
				updateAdapterListView(arraylist);
				// adapter.filterByTitle(selectedSkpd);
				popup.dismiss();
			}
		});
		
		View parentView = new View(getApplicationContext());
		BitmapDrawable drawable = new BitmapDrawable();
		popup.setBackgroundDrawable(drawable);
		popup.showAtLocation(parentView, Gravity.CENTER, 0, 0);
		
	}


}
